package com.video.main_video.manager.handle.userInfo;

import com.video.main_video.api.Api;
import com.video.main_video.common.staticData.StaticData;
import com.video.main_video.common.utils.ImgUtils;
import com.video.main_video.dao.entity.User;
import com.video.main_video.dao.request.userInfo.UpdateAvatarRequest;
import com.video.main_video.dao.response.userInfo.UpdateAvatarResponse;
import com.video.main_video.manager.handle.ApiHandler;
import com.video.main_video.manager.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Api
public class UpdateAvatarManager implements ApiHandler<UpdateAvatarRequest, UpdateAvatarResponse> {

    @Autowired
    UserMapper userMapper;
    @Transactional
    @Override
    public UpdateAvatarResponse handler(UpdateAvatarRequest updateAvatarRequest) {
        UpdateAvatarResponse res=new UpdateAvatarResponse();
        String fileId = saveAvatarToLocal(updateAvatarRequest.getAvatar());
        if ("".equals(fileId)){
            res.setCode(404);
            res.setError("创建文件夹失败");
            return res;
        }
        updateAvatar(fileId);
        res.setCode(200);
        res.setMsg("更新成功");
        return res;
    }

    private void updateAvatar(String avatar) {
        User user = new User();
        user.setId(StaticData.UserId);
        user.setAvatar(avatar);
        userMapper.updateById(user);
    }

    private String saveAvatarToLocal(String base64Avatar) {
        try {
            return ImgUtils.base64toPng(base64Avatar, "avatar\\");
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
